package com.zhao.retry.demo.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhao.retry.demo.entity.RetryRecord;
import com.zhao.retry.demo.mapper.RetryRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2020/5/20.
 *
 * @author zhao
 * @email 136689260@qq.com
 */
@Slf4j
@EnableScheduling
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableRetry(proxyTargetClass = true)
@Configuration
public class RetryConfig {

    @Autowired
    private RetryRecordMapper retryRecordMapper;

    @Autowired
    private ApplicationContext applicationContext;

    //每30秒执行一次
    @Scheduled(fixedRate = 1000 * 30)
    public void reportCurrentTime() {
        QueryWrapper<RetryRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        Page<RetryRecord> bodyPage = retryRecordMapper.selectPage(new Page<>(1, 10), queryWrapper);
        if (bodyPage.getSize() > 0) {
            List<RetryRecord> retryRecordList = bodyPage.getRecords();
            for (RetryRecord retryRecord : retryRecordList) {
                Class<?>[] parameterTypes = null;
                Object[] args = null;
                Method method =null;
                try {
                    Class<?> cls = Class.forName(retryRecord.getClassName());
                    Object instance = applicationContext.getBean(cls);
                    Map<String, String> paramMap = JSON.parseObject(retryRecord.getParam(), LinkedHashMap.class);
                    parameterTypes = new Class[paramMap.keySet().size()];
                    args = new Object[paramMap.keySet().size()];
                    Iterator<String> paramMapKeyIterator = paramMap.keySet().iterator();
                    int idx = 0;
                    while (paramMapKeyIterator.hasNext()) {
                        String key = paramMapKeyIterator.next();
                        parameterTypes[idx] = Class.forName(key);
                        args[idx] = JSON.parseObject(paramMap.get(key), parameterTypes[idx]);
                        idx++;
                    }
                    method = ReflectionUtils.findMethod(cls, retryRecord.getMethodName(), parameterTypes);
                    ReflectionUtils.makeAccessible(method);
                    log.info("args {} {}  ", parameterTypes, JSON.toJSONString(args));
                    Object result = ReflectionUtils.invokeMethod(method, instance, args);
                    log.info("result {} ", JSON.toJSONString(result));
                    retryRecord.setStatus(1);
                    retryRecordMapper.updateById(retryRecord);
                } catch (Exception e) {
                    log.error("retryRecord {} ", JSON.toJSONString(retryRecord), e);
                }
            }
        }
    }
}
